# -*- coding: utf-8 -*-
import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
import win32api, re
import win32com
import win32clipboard
import win32con,time
import pinyin,ctypes
import xlrd
from ctypes import windll
# from pymouse import PyMouse
from optparse import OptionParser
from PyQt5.QtWidgets import QMessageBox
from pymouse import PyMouse
from pykeyboard import PyKeyboard
from bot_log import BotLogger
from inv_model import *
import inv_config as config
from bot_ydm import C_YDM_HTTP as ydm


if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']


logger = BotLogger(os.path.basename(__file__), logname=1).getLogger()


def check_procname_exist(procname):
    """检查进程名是否存在"""
    try:
        wmi = win32com.client.GetObject('winmgmts:')
        proc_code_cov = wmi.ExecQuery("select * from Win32_Process where Name='%s'" % procname)
        if len(proc_code_cov) > 0:
            logger.info('Check ProName: {} Exist'.format(procname))
            return True
        return False
    except Exception as e:
        logger.error(str(e))
        return False


import win32gui

hwnd_title = dict()


def get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


# win32gui.EnumWindows(get_all_hwnd, 0)

for h, t in hwnd_title.items():
    if t is not "":
        print(h,t)
def mouse_move(x, y):
    """
    移动鼠标位置
    :param x: int, 目的横坐标
    :param y: int, 目的纵坐标
    :return: None
    """
    windll.user32.SetCursorPos(x, y)

def mouse_click(x=None, y=None,  press_time=0.0):
    """
    模拟鼠标点击
    :param x: int, 鼠标点击位置横坐标
    :param y: int, 鼠标点击位置纵坐标
    :return: None
    """
    print(1)
    if not x is None and not y is None:
        mouse_move(x, y)
        time.sleep(1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
def f1():
    hwnd = win32gui.FindWindow(None, u'增值税发票开票软件（税务UKey版）')
    # 将窗口放在前台，并激活该窗口
    win32gui.SetForegroundWindow(hwnd)
    # mouse_click(968, 602)

    # m = PyMouse()
    # # a = m.position()  # 获取当前坐标的位置
    # # print(a)
    #
    # m.move(968, 602)  # 鼠标移动到(x,y)位置
    # # a = m.position()
    # # print(a)
    # time.sleep(1)
    # m.click(365, 883,1)
    # m.click(365, 883,1)
    # m.release(365, 883,1)
    # time.sleep(1)
    # print(m.position())


    import pyautogui as pg
    pg.moveTo(980,610)
    pg.doubleClick()

#242 83  1210 685 968 602
# f1()
def Set_item(title):
    # hwnd = win32gui.FindWindow(None, u'增值税发票开票软件（税务UKey版）')
    hwnd = win32gui.FindWindow(None, title)
    # 将窗口放在前台，并激活该窗口
    win32gui.SetForegroundWindow(hwnd)
    # win32gui.SetWindowPos
    # Zoom_out(title):
    # hwnd = win32gui.FindWindow(None, title)
    # 将窗口放在前台，并激活该窗口
    # win32gui.CloseWindow(hwnd)
    # win32gui.ShowWindow(win32gui.FindWindow(None,title),win32con.SW_SHOW)


def left_click(x, y):
    # ctypes.windll.user32.SetCursorPos(68, 84)
    win32api.SetCursorPos([x, y])
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0,0, 0)

    time.sleep(1)

    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

    time.sleep(1)
    # win32api.SetCursorPos([x, y])
    # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    # time.sleep(2)
    # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
# Set_item()
# time.sleep(1)
# left_click(13,878)
# left_click(21,877)
# import xml.etree.ElementTree as ET

def Customer():
    Set_item('增值税发票开票软件（税务UKey版）')
    time.sleep(2)
    try:
        customer_name = 'cust.xml'
        left_click(197,379)
        time.sleep(3)
        left_click(1062,253)
        time.sleep(2)
        print('ooopop')
        left_click(200,178)
        time.sleep(2)
        # left_click(254,83)  # 导初
        # time.sleep(2)
        pwd = os.getcwd()
        # m = PyMouse()
        # k = PyKeyboard()
        # m.click(546, 74, 1, 1)
        # time.sleep(2)
        # k.type_string(str(pwd))
        # time.sleep(2)
        # k.press_key(k.enter_key)
        # k.release_key(k.enter_key)
        # time.sleep(2)
        # m.click(300, 466, 1, 1)
        # time.sleep(2)
        # k.type_string(customer_name)
        # time.sleep(2)
        # m.click(906, 531, 1, 1)
        # time.sleep(2)
        # m.click(777,442, 1, 1)
        # time.sleep(2)
        # m.click(711, 451, 1, 1)
        time.sleep(2)
        path = str(pwd+'\\'+customer_name)
        print(path)
        return path
    except Exception as e:
        logger.error(str(e))

def Customer_code(path):
    opnefile = xlrd.open_workbook(path)
    sheet_1 = opnefile.sheet_by_index(0)
    row_number = sheet_1.nrows
    col_number = sheet_1.ncols
    print(sheet_1)
    print(row_number)
    print(col_number)
    Customer_code_list = []
    # compay_name_list = []
    # customer_code_list = []
    # tax_num_list = []
    # id_num_list = []
    # address_list = []
    # account_bank_list = []
    # email_list = []
    # num = int(str(time.strftime("%Y%m%d%H%M", time.localtime()))[2:])
    # cust_num = num
    for i in range(1,row_number):
        Customer_code = []
        compay_name = sheet_1.row_values(i)[0]
        Customer_code.append(compay_name)
        my_re = re.compile(r'[A-Za-z]', re.S)
        res = re.findall(my_re, str(sheet_1.row_values(i)[0]))
        # compay_name_list.append(sheet_1.row_values(i)[0])
        # if str(sheet_1.row_values(i)[0]).isalpha():
        if len(res):
            # customer_code_list.append((sheet_1.row_values(i)[0]).upper())
            customer_code=sheet_1.row_values(i)[0].upper()
        else:
            customer_code=pinyin.get_initial(sheet_1.row_values(i)[0], delimiter="").upper()
        print(customer_code)
        Customer_code.append(customer_code)
        Customer_code.append(sheet_1.row_values(i)[1])
        # tax_num=sheet_1.row_values(i)[1]
        Customer_code.append(sheet_1.row_values(i)[2])
        # id_num=sheet_1.row_values(i)[2]
        Customer_code.append(sheet_1.row_values(i)[3])
        # address=sheet_1.row_values(i)[3]
        Customer_code.append(sheet_1.row_values(i)[4])
        # account_bank=sheet_1.row_values(i)[4]
        Customer_code.append(sheet_1.row_values(i)[5])
        Customer_code_list.append(Customer_code)
        # email=sheet_1.row_values(i)[5]
        # cust = Customer(cust_num,compay_name,customer_code,tax_num,id_num,address,account_bank,email,status='init')
        # if not Customer.create_customer(cust) is None :
        #     return None
    return Customer_code_list
    # print(compay_name_list)
    # print(customer_code_list)
    # print(tax_num_list)
    # print(id_num_list)
    # print(address_list)
    # print(account_bank_list)
    # print(email_list)
    # return compay_name_list,customer_code_list,tax_num_list,id_num_list,address_list,account_bank_list,email_list
# Customer_code('inv.xls')

def Customer_xml(path1,datalist):
    with open(path1,'r') as f:
        lines = f.readlines()
        alist =[]
        for line in lines:
            alist.append(line.strip())
            # print(alist.append(line.strip()))
        print(alist[-3])
        PID_start = alist[-3].find('O_PID="')
        PID_end = alist[-3].find('" YHZH')
        PID = alist[-3][PID_start+7:PID_end]
        # print(alist[-3][alist[-3].find('O_PID="')+7:alist[-3].find('" BM')])
        print(PID)
        BM_start= alist[-3].find('BM="')
        BM_end=alist[-3].find('" KZ1')
        BM = alist[-3][BM_start+4:BM_end]
        # print(alist[-3][BM_start+4:BM_end])
        print(BM)
        # print(type(alist[-3]))
        # print(f.readlines())
        # return alist,PID, BM
    pathname = 'a.xml'
    pwd = os.getcwd()
    with open(pathname,'w') as f1:
        for i in alist[0:6]:
            f1.write(i)
            f1.write('\n')
        for data in datalist:
            # f1.write('<Row O_PID="100" BM="10000006" YHZH="" YJDZ="1" DZ="" MC="ff" KZ1="" NSRSBH="" JM="FF" PID="100" O_BM="10000006"/>')
            BM = int(BM)+1
            f1.write('<Row BM="'+str(BM)+'" YJDZ="'+str(data[-1])+'" JM="'+str(data[1])+'" NSRSBH="'+str(data[2])+'" MC="'+str(data[0])+'" YHZH="'+str(data[-2])+'" O_BM="'+str(BM)+'" KZ1="'+str(data[3])+'" O_PID="'+str(PID)+'" PID="'+str(PID)+'" DZ="'+str(data[-3])+'"/>')
            f1.write('\n')
        for j in alist[-2:]:
            f1.write(j)
            f1.write('\n')
            # f1.write(alist[0])
            # f1.write(alist[1])
            # f1.write(alist[2])
            # f1.write(alist[3])
    return pwd
# w1()
# jl = "<Row O_PID="100" BM="10000004" YHZH="" YJDZ="1" DZ="" MC="dd" KZ1="" NSRSBH="" JM="DD" PID="100" O_BM="10000004"/>"
# jl.find
# Customer_xml('cust.xml')
def upload_customer(upath):
    m = PyMouse()
    k = PyKeyboard()
    m.click(164,83,1,1)
    time.sleep(2)
    m.click(618,73,1,1)
    time.sleep(2)
    k.type_string(str(upath))
    time.sleep(2)
    k.press_key(k.enter_key)
    k.release_key(k.enter_key)
    time.sleep(2)
    k.press_key(k.enter_key)
    k.release_key(k.enter_key)
    time.sleep(2)
    m.click(349,252,1,1)
    time.sleep(2)
    m.click(906,537,1,1)
    time.sleep(2)
    m.click(718,452,1,1)
    time.sleep(2)
    m.click(1294,50,1,1)


def Commodity_code(path):
    Set_item('增值税发票开票软件（税务UKey版）')
    time.sleep(2)
    opnefile = xlrd.open_workbook(path)
    sheet_1 = opnefile.sheet_by_index(1)
    row_number = sheet_1.nrows
    col_number = sheet_1.ncols
    print(sheet_1)
    print(row_number)
    print(col_number)
    Commodity_code_list = []
    # commodity_name_list = []
    # commodity_code_list = []
    # model_list = []
    # unit_list = []
    # price_list = []
    num = int(str(time.strftime("%Y%m%d%H%M", time.localtime()))[2:])
    cust_num = num
    for i in range(1,row_number):
        Commodity_code1 = []
        # commodity_name_list.append(sheet_1.row_values(i)[0])
        commodity_name=sheet_1.row_values(i)[0]
        Commodity_code1.append(commodity_name)
        my_re = re.compile(r'[A-Za-z]', re.S)
        res = re.findall(my_re, str(sheet_1.row_values(i)[0]))
        if len(res):
            # commodity_code_list.append((sheet_1.row_values(i)[0]).upper())
            commodity_code=sheet_1.row_values(i)[0].upper()
        else:
            # commodity_code_list.append(pinyin.get_initial(sheet_1.row_values(i)[0], delimiter="").upper())
            commodity_code=pinyin.get_initial(sheet_1.row_values(i)[0], delimiter="").upper()
        Commodity_code1.append(commodity_code)
        # model_list.append(sheet_1.row_values(i)[1])
        model=sheet_1.row_values(i)[1]
        Commodity_code1.append(model)
        # unit_list.append(sheet_1.row_values(i)[2])
        unit=sheet_1.row_values(i)[2]
        Commodity_code1.append(unit)
        # price_list.append(sheet_1.row_values(i)[3])
        price=sheet_1.row_values(i)[3]
        Commodity_code1.append(price)
        Commodity_code_list.append(Commodity_code1)
    print(Commodity_code_list)
        # commodity = Commodity(cust_num,commodity_name,commodity_code,model,unit,price,status='init')
        # if not Commodity.create_commodity(commodity) is None :
        #     return None
    # return commodity_name_list,commodity_code_list,model_list,unit_list,price_list
    return Commodity_code_list
def Invoicing(path):
    Set_item('增值税发票开票软件（税务UKey版）')
    time.sleep(2)
    opnefile = xlrd.open_workbook(path)
    sheet_1 = opnefile.sheet_by_index(2)
    row_number = sheet_1.nrows
    col_number = sheet_1.ncols
    print(sheet_1)
    print(row_number)
    print(col_number)
    invoice_list = []
    for i in range(1,row_number):
        invoice = []
        invoice.append(sheet_1.row_values(i)[0])
        invoice.append(sheet_1.row_values(i)[1])
        invoice.append(sheet_1.row_values(i)[2])
        invoice.append(sheet_1.row_values(i)[3])
        invoice.append(sheet_1.row_values(i)[4])
        invoice.append(sheet_1.row_values(i)[5])
        invoice.append(sheet_1.row_values(i)[6])
        invoice.append(sheet_1.row_values(i)[7])
        invoice_list.append(invoice)
    if invoice_list:
        m = PyMouse()
        k = PyKeyboard()
        m.click(195,213, 1, 1)
        time.sleep(2)
        m.click(538,614, 1, 1)
        time.sleep(5)
        # 1043,167  132 43
        img = save_img(1043,167,132,43,'剩余')
        name = ydm().get_code(filename=img, typeid=1)
        print(name)
        if int(name) != 0:
            m.click(1286,53, 1, 1)
            time.sleep(2)
            # m.click(865,428, 1, 1)
            # time.sleep(2)
            # m.click(1059,428, 1, 1)
            # time.sleep(8)
            print('发票填开')
            print(invoice_list)
            for inv in invoice_list:
                print(inv)
                num = ''
                price = ''
                price1 = ''
                if float(inv[-2]) > 99999.99:
                    remainder = float(inv[-2]) % 99999.99
                    if remainder != 0:
                        num = int(float(inv[-2]) / 99999.99) + 1
                        price = 99999.99
                        price1 = float(inv[-2]) - (num -1) * 99999.99
                        price1 = round(price1,2)
                    else:
                        num = int(float(inv[-2]) / 99999.99)
                        price = 99999.99

                else:
                    num = 1
                    price = inv[-2]
                    price = round(price,2)
                print(inv[-2])
                if num == 1:
                    m.click(865, 428, 1, 1)
                    time.sleep(2)
                    m.click(1059, 428, 1, 1)
                    time.sleep(8)
                    m.click(446, 274, 1, 2)
                    time.sleep(2)
                    if inv[0] in '青岛灵动未来科技有限公司':
                        m.click(504, 234, 1, 2)
                        time.sleep(2)
                    m.click(337, 381, 1, 2)
                    time.sleep(2)
                    if inv[3] in '装卸搬运':
                        # m.click(487, 586, 1, 2)
                        # m.click(493,546, 1, 2)
                        m.click(494,505, 1, 2)
                        time.sleep(2)
                    print(11111111)
                    print(price)
                    print(price1)
                    time.sleep(2)
                    m.click(534,381,1,1)
                    time.sleep(2)
                    k.type_string(str(inv[4]))
                    time.sleep(2)
                    m.click(626,384,1,1)
                    time.sleep(2)
                    k.type_string(str(inv[5]))
                    # k.type_string(str('zhang'))
                    time.sleep(2)
                    k.press_key(k.space_key)
                    k.release_key(k.space_key)
                    m.click(702,381,1,1)
                    time.sleep(2)
                    k.type_string(str(1))  # 数量
                    time.sleep(2)
                    m.click(791,381,1,1)
                    time.sleep(2)
                    k.type_string(str(price))
                    time.sleep(2)
                    m.click(882,383,1,1)
                    time.sleep(2)
                    if float(inv[-1]) == 0.01:
                        m.click(1022,379,1,1)
                        time.sleep(2)
                        m.click(1008,397,1,1)
                        time.sleep(2)
                    if float(inv[-1]) == 0.03:
                        m.click(1022,379,1,1)
                        time.sleep(2)
                        m.click(1008,406,1,1)
                        time.sleep(2)
                    if float(inv[-1]) == 0.05:
                        m.click(1022,379,1,1)
                        time.sleep(2)
                        m.click(1008,415,1,1)
                        time.sleep(2)
                    if float(inv[-1]) == 0:
                        m.click(1022,379,1,1)
                        time.sleep(2)
                        m.click(1008,424,1,1)
                        time.sleep(2)
                    # m.click(338,744,1,1)   # 收款人
                    # time.sleep(2)
                    # for u in range(6):
                    #     k.press_key(k.delete_key)
                    #     k.release_key(k.delete_key)
                    # time.sleep(2)
                    # k.type_string(str(price))
                    # time.sleep(2)
                    # k.press_key(k.space_key)
                    # k.release_key(k.space_key)
                    # time.sleep(2)
                    # m.click(563,743,1,1)  # 复核人
                    # time.sleep(2)
                    # for u in range(6):
                    #     k.press_key(k.delete_key)
                    #     k.release_key(k.delete_key)
                    # time.sleep(2)
                    # k.type_string(str(price))
                    # time.sleep(2)
                    # k.press_key(k.space_key)
                    # k.release_key(k.space_key)
                    # time.sleep(2)
                    m.click(713,794,1,1)      #  开具
                    time.sleep(8)

                    # m.click(834,536,1,1)     # 发送邮件
                    # time.sleep(2)
                    # m.click(740,370,1,1)
                    # time.sleep(2)
                    # time.sleep(2)
                    # for l in range(30):
                    #     k.press_key(k.backspace_key)
                    #     k.release_key(k.backspace_key)
                    # time.sleep(2)
                    # k.type_string(str('jack_roc@126.com'))  # 输入邮箱
                    # time.sleep(2)
                    # m.click(695,511,1,1)  # 提交
                    # time.sleep(5)
                    # m.click(715,451,1,1)  # 确定
                    # time.sleep(3)
                    m.click(674,534,1,1)  # 是否继续 开具发票 取消
                    time.sleep(2)
                    # m.click(593,542,1,1)  #确定
                    # time.sleep(2)
                    time.sleep(15)

                else:
                    m.click(865, 428, 1, 1)
                    time.sleep(2)
                    m.click(1059, 428, 1, 1)
                    time.sleep(8)

                    print(22222222)
                    print(price)
                    print(price1)
                    for i in range(1,num+1):
                        m.click(446, 274, 1, 2)
                        time.sleep(2)

                        if inv[0] in '青岛灵动未来科技有限公司':
                            m.click(504, 234, 1, 2)
                            time.sleep(2)
                        m.click(337, 381, 1, 2)
                        time.sleep(2)
                        if inv[3] in '麻将':
                            m.click(487, 586, 1, 2)
                            time.sleep(2)
                        time.sleep(2)
                        m.click(534, 381, 1, 1)
                        time.sleep(2)
                        k.type_string(str(inv[4]))
                        time.sleep(2)
                        m.click(626, 384, 1, 1)
                        time.sleep(2)
                        k.type_string(str(inv[5]))
                        time.sleep(2)
                        m.click(702, 381, 1, 1)
                        time.sleep(2)
                        k.type_string(str(i))
                        time.sleep(2)
                        m.click(791, 381, 1, 1)
                        time.sleep(2)
                        if i == (num):
                            k.type_string(str(price1))
                        else:
                            k.type_string(str(price))
                        time.sleep(2)
                        m.click(882, 383, 1, 1)
                        time.sleep(2)
                        if float(inv[-1]) == 0.01:
                            m.click(1022, 379, 1, 1)
                            time.sleep(2)
                            m.click(1008, 397, 1, 1)
                            time.sleep(2)
                        if float(inv[-1]) == 0.03:
                            m.click(1022, 379, 1, 1)
                            time.sleep(2)
                            m.click(1008, 406, 1, 1)
                            time.sleep(2)
                        if float(inv[-1]) == 0.05:
                            m.click(1022, 379, 1, 1)
                            time.sleep(2)
                            m.click(1008, 415, 1, 1)
                            time.sleep(2)
                        if float(inv[-1]) == 0:
                            m.click(1022, 379, 1, 1)
                            time.sleep(2)
                            m.click(1008, 424, 1, 1)
                            time.sleep(2)
                            # m.click(338,744,1,1)   # 收款人
                            # time.sleep(2)
                            # for u in range(6):
                            #     k.press_key(k.delete_key)
                            #     k.release_key(k.delete_key)
                            # time.sleep(2)
                            # k.type_string(str(price))
                            # time.sleep(2)
                            # k.press_key(k.space_key)
                            # k.release_key(k.space_key)
                            # time.sleep(2)
                            # m.click(563,743,1,1)  # 复核人
                            # time.sleep(2)
                            # for u in range(6):
                            #     k.press_key(k.delete_key)
                            #     k.release_key(k.delete_key)
                            # time.sleep(2)
                            # k.type_string(str(price))
                            # time.sleep(2)
                            # k.press_key(k.space_key)
                            # k.release_key(k.space_key)
                            # time.sleep(2)
                        m.click(713, 794, 1, 1)
                        time.sleep(8)
                        m.click(834, 536, 1, 1)
                        time.sleep(2)
                        m.click(740, 370, 1, 1)
                        time.sleep(2)
                        # k.press_key(k.control_key) # 按住alt键
                        # k.tap_key('A') # 点击tab键
                        # k.release_key(k.control_key) # 松开alt键
                        time.sleep(2)
                        for l in range(30):
                            k.press_key(k.backspace_key)
                            k.release_key(k.backspace_key)
                        time.sleep(2)
                        k.type_string(str('jack_roc@126.com'))  # 输入邮箱
                        time.sleep(2)
                        k.press_key(k.enter_key)
                        k.release_key(k.enter_key)
                        time.sleep(2)
                        m.click(695, 511, 1, 1)  # 提交
                        time.sleep(5)
                        m.click(715, 451, 1, 1)  # 确定
                        time.sleep(3)
                        # m.click(674, 534, 1, 1)  # 是否继续 开具发票 取消
                        # time.sleep(2)
                        m.click(593,542,1,1)  #确定
                        time.sleep(2)
                        time.sleep(15)

            m.click(1295, 54, 1, 1)  # 返回
            time.sleep(2)


        else:
            print('没有剩余发票可以开')
def xi():
    Set_item('增值税发票开票软件（税务UKey版）')
    m = PyMouse()
    k = PyKeyboard()
    time.sleep(2)
    m.click(740, 370, 1, 1)
    time.sleep(2)
    # k.press_keys([k.control_key, 'a'])
    # k.release_key([k.control_key, 'a'])
    k.press_key(k.control_key)  # 按住alt键
    k.tap_key('A')  # 点击tab键
    k.release_key(k.control_key)  # 松开alt键
    time.sleep(2)
    for l in range(30):
        k.press_key(k.backspace_key)
        k.release_key(k.backspace_key)
    time.sleep(2)
    # k.type_string('jj')
# xi()
# Commodity_code('inv.xls')
def Commodity(datalist):
    print(datalist)
    m = PyMouse()
    k = PyKeyboard()
    m.click(222,384, 1, 1)
    time.sleep(2)
    m.click(1080,601, 1, 1)
    time.sleep(4)
    m.click(216,174, 1, 1)
    time.sleep(2)
    for data in datalist:
        m.click(469,190, 1, 1)
        time.sleep(2)
        m.click(652,269, 1, 1)
        time.sleep(2)
        googs_name = pinyin.get(data[0], delimiter="")
        k.type_string(str(googs_name))
        time.sleep(2)
        k.press_key(k.space_key)
        k.release_key(k.space_key)
        m.click(668,321, 1, 1)
        time.sleep(2)
        # k.type_string(str(data[1]))
        time.sleep(2)
        m.click(668,480, 1, 1)
        time.sleep(2)
        k.type_string(str(data[2]))
        time.sleep(2)
        m.click(656,532, 1, 1)
        time.sleep(2)
        k.type_string(str(data[3]))
        time.sleep(2)
        m.click(683,583, 1, 1)
        time.sleep(2)
        k.type_string(str(data[-1]))
        time.sleep(2)
        m.click(657,634,1,1)
        time.sleep(2)
        m.click(717,448,1,1)
        time.sleep(2)
        m.click(1268,272,1,1)
        time.sleep(2)
        m.click(919,131,1,1)
        time.sleep(2)
        # k.type_string(str(data[0]))
        # time.sleep(2)
        # k.type_string('lanqiu')
        k.type_string(str(googs_name))
        time.sleep(2)
        k.press_key(k.space_key)
        k.release_key(k.space_key)
        m.click(1030,129,1,1)
        time.sleep(8)
        # 789,196   125  40
        img = save_img(789,196,125,40,'商品')
        name = ydm().get_code(filename=img, typeid=32)
        time.sleep(5)
        print(name)
        if '无数据' in name:
            m.click(1293,49,1,1)
            time.sleep(2)
        else:
            m.click(487,211,1,1)
            time.sleep(2)
            m.click(612,432,1,1)
            time.sleep(2)
    m.click(1298,42,1,1)
    time.sleep(2)

# import pinyin


# def getStrAllAplha(str):
#     return pinyin.get_initial(str, delimiter="").upper()
#
#
# def getStrFirstAplha(str):
#     str = getStrAllAplha(str)
#     str = str[0:1]
#     return str.upper()
#
#
# str = '你好在哪来'
#
# print(getStrAllAplha(str))
# print(getStrFirstAplha(str))

# def reset_window_pos(targetTitle):
def reset_window_pos():
    hWndList = []
    titlelist = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    for hwnd in hWndList:
        clsname = win32gui.GetClassName(hwnd)
        title = win32gui.GetWindowText(hwnd)
        titlelist.append(title)
        # print(clsname)
        # print(title)
        # if 'tax – utils.py' in title:
        #     wnd = win32gui.FindWindow(None,title)
        #     win32gui.CloseWindow(wnd)
    # print(hWndList)
        # if (title.find(targetTitle) >= 0):  # 调整目标窗口到坐标(600,300),大小设置为(600,600)
        #     win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 600, 300, 600, 600, win32con.SWP_SHOWWINDOW)
    return titlelist
# reset_window_pos("windowName")
# reset_window_pos()
import pyautogui as gui

def test1():
    # Set_item('增值税发票开票软件（税务UKey版）')
    gui.moveTo(216, 879, duration=1)
    time.sleep(0.3)
    gui.click(216, 879, button='left', duration=1)
    #216 879
    time.sleep(0.3)
    print(1)
    gui.moveTo(980,600,duration=1)
    time.sleep(0.3)
    print(2)
    # gui.doubleClick(980,600,duration=1)
    print(3)
    gui.click(980,600,button='left',duration=1)
# test1()

def processing_result(data):

    pass

def online_issue_inv():
    Set_item('增值税发票开票软件（税务UKey版）')
    m = PyMouse()
    k = PyKeyboard()
    m.click(205,212, 1, 1)
    time.sleep(2)
    m.click(525,417, 1, 1)
    time.sleep(2)
    for i in range(5):
        m.click(1251,131, 1, 1)
        time.sleep(4)
        img = save_img(644,312, 230, 75, 'inv_static')
        name = ydm().get_code(filename=img, typeid=32)
        print(name)
        if '没有查询到可以领取的发票' in name:
            m.click(723,449,1,1)
            time.sleep(2)
            m.click(1291,43,1,1)
            time.sleep(3)
            break
        else:
            img1 = save_img(1103,194, 196, 42, 'inv_static1')
            name1 = ydm().get_code(filename=img1, typeid=32)
            print(name1)
            if '未分发' in name1:
                m.click(1187,211,1,1)
                time.sleep(2)
                m.click(1019,471,1,1)
                time.sleep(8)
                m.click(718,452,1,1)
                time.sleep(5)
                m.click(1291, 43, 1, 1)
                time.sleep(3)
def load_config():
    """加载配置文件"""
    try:
        parser = OptionParser(prog='salary', usage="%prog [options]")

        parser.add_option("-c", "--config_path", action="store", type="string", dest="config_path", help="配置文件路径")
        (options, args) = parser.parse_args()

        config_path = options.config_path
        if not config_path:
            config_path = os.getcwd() + '/inv.conf'
        if not os.path.exists(config_path):
            logger.error('The config file %s does not exist' % config_path)
            return False
        if not os.path.isfile(config_path):
            logger.error('The config path %s is not a file' % config_path)
            return False

        try:
            config.configure(config_path)
        except Exception as e:
            logger.error(str(e))
            return False
        return True
    except Exception as e:
        logger.error(str(e))
        return False

def informationMsgBox(win, title, msg):
    """消息对话提示框"""
    """"""
    result = QMessageBox.information(win, title, msg, QMessageBox.Ok)
    if result == 1024:
        return True
    return False

def save_img(x,y,w,h,img_name):
    import pyautogui
    # import cv2

    try:
        # img = pyautogui.screenshot(region=[403,263, 100, 100])  # x,y,w,h
        img = pyautogui.screenshot(region=[x,y, w, h])  # x,y,w,h
        img_name = str(img_name) + '.png'
        img.save(img_name)
        return img_name
    except Exception as e:
        logger.error(str(e))
    # img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# save_img(610,530,120,30,'7天提示')
# Set_item('增值税发票开票软件（税务UKey版）')
# left_click(973,596)
# left_click(738,544)
# time.sleep(5)
# from pymouse import *
# m = PyMouse()
# # m.click(116,878,1,1)
# time.sleep(2)
# # m.click(738,544,2,3)
# # # m.move(21,879)
# # print(m.position())
# m.click(973,604,1,2)
# time.sleep(2)

def QuickMacro_login():
    titlelist = reset_window_pos()
    for titile in titlelist:
        if '按键精灵' in titile:
            Set_item(titile)
    time.sleep(2)
    left_click(523,288)
    time.sleep(2)

# QuickMacro_login()
import xml.etree.ElementTree as ET
def reada_xml():
    tree = ET.parse('cust.xml')
    root = tree.getroot()
    print(root)
    print(root.tag)
    # nodes = root.findall('KHXX')
    # print(nodes[-1])
    # for node in nodes:
    #     print(node.get('BM'))
    BM = ''
    PID = ''
    for element in root.iter('Row'):
        # print(element.tag)
        # print(element.attrib)
        # print(element.attrib.get('BM'))
        BM = int(element.attrib.get('BM'))
        PID = int(element.attrib.get('PID'))
    print(BM)
    print(PID)


def login():
    Set_item('增值税发票开票软件（税务UKey版）')
    time.sleep(2)
    # img = save_img(894, 647, 122, 38, 'uname')
    img = save_img(864,300, 75, 35, 'uname') # 865,298
    time.sleep(2)
    code = ydm().get_code(filename=img, typeid=32)
    print(code)
    time.sleep(5)
    left_click(975,602)
    time.sleep(8)
    return code

def colse_prompt():
    Set_item('增值税发票开票软件（税务UKey版）')
    time.sleep(2)
    try:
        left_click(736, 545)
        time.sleep(5)
        left_click(602, 544)
        time.sleep(5)
        left_click(921,544)
        print(55)
    except Exception as  e:
        logger.error(str(e))
    # img = save_img(610, 530, 120, 30, '7天提示')
    # try:
    #     code = ydm().get_code(filename=img, typeid=7)
    #     print(55566)
    #     print(code)
    #     if '7天内不在提示' in code:
    #         left_click(736, 545)
    #         time.sleep(5)
    #         left_click(602, 544)
    #     else:
    #         logger.info('没有友情提示')
    # except Exception as e:
    #     logger.error(str(e))

def shibie_img(img):
    # end_time = ''
    start_time = time.time()
    code = ydm().get_code(filename=img, typeid=7)
    if '7天内不在提示' in code:
        end_time = time.time()
        print(code)
        print(end_time-start_time)
    print('kk')
    print(code)
# shibie_img('7天提示.png')

def sum_upload(code):
    if code:
        code = code.strip()
    day_now = time.localtime()
    day = int(day_now.tm_mday)
    if day in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
        # day_now = time.localtime()
        # day = int(day_now.tm_mday)
        # if day in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
        #     left_click(1163,411)
        #     time.sleep(3)
        #     left_click(170,202)
        #     time.sleep(3)
        #     left_click(674,449)
        #     time.sleep(3)
        #
        #     time.sleep(5)
        #     left_click(264,203)
        #     time.sleep(3)
        #     left_click(675,453)
        #     time.sleep(3)
        # else:
        left_click(1295,46)
        time.sleep(5)
        img = save_img(773,383,111,35,'upload_sum')
        time.sleep(2)
        name1 = ydm().get_code(filename=img, typeid=32)
        print(name1)
        time.sleep(8)
        img1 = save_img(882,385,111,35,'reverse_writing_monitor')
        time.sleep(2)
        name2 = ydm().get_code(filename=img1, typeid=32)
        print(name2)
        time.sleep(8)
        if '已上报汇总' in name1:
            logger.info('已上报汇总')
            print('已上报汇总')
        else:
            left_click(995,298)
            time.sleep(2)
            left_click(1163, 411)
            time.sleep(3)
            left_click(170, 202)
            time.sleep(3)
            left_click(674, 449)
            time.sleep(3)
        if '已反写' in name2:
            logger.info('已反写')
            print('一反写')
        else:
            left_click(993,295)
            time.sleep(2)
            left_click(264, 203)
            time.sleep(3)
            left_click(675, 453)
            time.sleep(3)
        sumupload = Sumupload(code,1,1)
        left_click(758,558)
        if create_sumupload(sumupload) is None:
            print('添加到sumupload中')
            pass
    else:
        if list_sumupload(code):
            logger.info('Ukey' + str(code) + '已上传汇总、已反写')
            # left_click(758, 558)
            time.sleep(2)
        else:
            print(code)

